package com.game.utils;

import game.message.Message;
import game.utils.WriteUtil;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;

public class MessageUtil
{
  protected static Logger log = Logger.getLogger(MessageUtil.class);

  public static int order = 0;

  public static Object lock = new Object();

  public static void tellSession(IoSession session, Message message) {
    WriteUtil.write(session, message);
  }

  public static void tellInnerSession(IoSession session, Message message) {
    IoBuffer ioBuffer = IoBuffer.allocate(100);
    int length = 0;
    ioBuffer.setAutoExpand(true);
    ioBuffer.setAutoShrink(true);
    ioBuffer.putInt(message.getId());
    ioBuffer.putInt((int)(System.currentTimeMillis() / 1000L));
    message.write(ioBuffer);
    ioBuffer.flip();
    length = ioBuffer.limit();
    IoBuffer buf = IoBuffer.allocate(length + 8);
    buf.putInt(length + 4);
    Object order = session.getAttribute("order");
    if (order == null) {
      session.setAttribute("order", Integer.valueOf(0));
    }

    int orderId = Integer.parseInt(session
      .getAttribute("order")
      .toString());
    int ordercp = orderId;
    ordercp ^= 512;
    ordercp ^= length;
    buf.putInt(ordercp);
    synchronized (lock) {
      orderId++;
      session.setAttribute("order", Integer.valueOf(orderId));
    }
    buf.put(ioBuffer);
    buf.flip();

    WriteFuture writer = session.write(buf);
    try {
      writer = writer.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    try {
      if (!writer.isWritten())
        log.error(writer.getException());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static String castListToString(List<String> list) {
    StringBuffer buf = new StringBuffer();
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
      Object object = iter.next();
      buf.append(",").append(object.toString());
    }
    if (buf.length() > 0)
      buf.deleteCharAt(0);
    return "{" + buf.toString() + "}";
  }
}